import { Inject, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository } from "typeorm";
import { PostEntity } from "@entity/system/post.entity";
import { ListPostDTO, CreatePostDTO, UpdatePostDTO } from "@dto/system/post.dto";
import { DownloadExcelService } from "@service/common/downloadExcel";
import { resBuild } from "@utils/resBuild";
import { checkKeyIsExist } from "@utils/serviceHelp";
import { getOperator } from "@utils";

@Provide()
export class PostService {
  @Inject()
  ctx: Context;

  @Inject()
  downloadExcelService: DownloadExcelService;

  @InjectEntityModel(PostEntity)
  postEntity: Repository<PostEntity>;

  // 列表
  async list(queryParams: ListPostDTO) {
    const queryBuilder = this.postEntity.createQueryBuilder('entity');
    if(queryParams.postName) {
      queryBuilder.andWhere(`entity.postName like "%${queryParams.postName}%"`)
    }
    if(queryParams.postCode) {
      queryBuilder.andWhere(`entity.postCode like "%${queryParams.postCode}%"`)
    }
    if(queryParams.status) {
      queryBuilder.andWhere(`entity.status = ${queryParams.status}`)
    }
    if(queryParams.pageNum && queryParams.pageSize) {
      queryBuilder.skip((queryParams.pageNum - 1) * queryParams.pageSize).take(queryParams.pageSize)
    }

    queryBuilder.addOrderBy('entity.postSort', 'ASC')
    queryBuilder.addOrderBy('entity.createTime', 'DESC')

    const [rows, total] = await queryBuilder.getManyAndCount()
    return resBuild.list(rows, total)
  }

  // 添加
  async create(post: CreatePostDTO) {
    // 新增之前先判断是否已存在
    await checkKeyIsExist(this.postEntity,'postName', post.postName)
    const myEntity = this.postEntity.create(post);
    myEntity.setCreateBy(getOperator(this.ctx))
    await this.postEntity.save(myEntity);
    return resBuild.success()
  }

  // 删除
  async delete(postId: string) {
    const ids = postId.split(',').map(id => Number(id));
    await this.postEntity.delete(ids);
    return resBuild.success()
  }

  // 修改
  async update(post: UpdatePostDTO) {
    const myEntity = this.postEntity.create(post);
    myEntity.setUpdateBy(getOperator(this.ctx))
    await this.postEntity.save(myEntity);
    return resBuild.success()
  }

  // 详情
  async detail(postId: number) {
    const detailInfo = await this.postEntity.findOneBy({
      postId,
    });
    return resBuild.data(detailInfo)
  }

  // 导出
  async export(queryParams: ListPostDTO) {
    let headers = [
      { label: "岗位编号", prop: "postId", },
      { label: "岗位编码", prop: "postCode", },
      { label: "岗位名称", prop: "postName", },
      { label: "岗位排序", prop: "postSort", },
      { label: "状态", prop: "status", },
      { label: "创建时间", prop: "createTime", width: 25 },
    ];
    const { rows } = await this.list(queryParams)
    return this.downloadExcelService.downloadExcel({
      headers: headers,
      data: rows,
      sheetName: '岗位信息',
    });
  }
}
